import axios from 'axios';
// import { message } from 'antd';

// import Codes from '../utils/code';
import { API_DOMAIN, TOKEN_ERROR, TOKEN_INVALID } from '../utils/constants';
import API from '../api/auth/index';

const instance = axios.create({
  baseURL: `${API_DOMAIN}`,
});

instance.interceptors.request.use((config) => {
  const axiosConfig = config;
  const urlWithoutToken = ['login'];
  let { url } = axiosConfig;
  // axiosConfig.headers['User-Agent'] = 'web';
  if (urlWithoutToken.indexOf(url) === -1) {
    // set header if not login
    const accessToken = window.localStorage.getItem('accessToken');
    const refreshToken = window.localStorage.getItem('refreshToken');
    axiosConfig.headers['Access-Token'] = accessToken;
    axiosConfig.headers['Refresh-Token'] = refreshToken;
  }
  if (url.indexOf('getCaptchaImage') >= 0 || url.indexOf('xcxQrCode') >= 0) {
    axiosConfig.responseType = 'blob';
  }
  if (url.indexOf('getCaptchaImage') >= 0) {
    axiosConfig.responseType = 'blob';
  }
  if(url.indexOf('.htm?') === -1){
      url += '.htm';
  }

  axiosConfig.url = url;
  return axiosConfig;
}, error => Promise.reject(error));

instance.interceptors.response.use(async (response) => {
  const { data, status } = response;
  if (status !== 200) {
    return Promise.reject(new Error('请求失败'));
  }
  const { code } = data;
  if (code !== 1 && code !== undefined) {
    // message.error(Codes[code]);
    if (code === TOKEN_ERROR) {
      window.location.href = '/';
    }
    // if response code is token invalid, then
    // send request to get new token and put into localstorage
    if (code === TOKEN_INVALID) {
      const res = await API.updateAccessToken();
      const { code, data } = res; // eslint-disable-line
      if (code === 1) {
        window.localStorage.setItem('accessToken', data);
      }else{
          window.localStorage.removeItem('accessToken');
          window.localStorage.removeItem('refreshToken');
      }
    }
  }
  return data;
}, error => Promise.reject(error));

export default instance;
